from rest_framework import serializers
from api import models
from rest_framework.serializers import ModelSerializer


# 写一个类继承 ListSerializer, 重写update方法, 因为update方法没更新功能
class BookListSerializer(serializers.ListSerializer):
    # def create(self, validated_data):
    #     print(validated_data)
    #     return super().create(validated_data)

    def update(self, instance, validated_data):
        """

        :param instance: 对象列表
        :param validated_data: 清洗后的数据
        :return:
        """
        """
        def create(self, validated_data):
            return [
                self.child是 BookModelSerializer 对象
                self.child.create(attrs) for attrs in validated_data
            ]
        """
        print('instance:', instance)
        # instance: [<QuerySet [<Book: 世界互联>]>, <QuerySet [<Book: 红楼梦>]>]
        print('data:', validated_data)
        # data:
        # [{'name': '世界互联11', 'price': Decimal('12.00'), 'publish': <Publish: 东京出版社>,
        # 'authors': [<Author: AK>, <Author: AKW>]},
        # {'name': '世界互联8', 'price': Decimal('12.00'), 'publish': <Publish: 南京出版社>, '
        # authors': [<Author: AK>, <Author: AKW>]}]
        # 保存数据
        # self.child是BookModelSerializer对象
        print(self.child)
        return [
            # self.child.update(对象, 字典) for attrs in validated_data
            self.child.update(instance[i], attrs) for i, attrs in enumerate(validated_data)
        ]


# 如果序列化的是数据库表，尽量使用ModelSerializer
class BookModelSerializer(serializers.ModelSerializer):
    # 第一种 只序列化可以 反序列化有问题
    # publish = serializers.CharField(source='publish.name')
    # 第2种 在models类中写方法

    class Meta:
        list_serializer_class = BookListSerializer
        model = models.Book
        # fields = '__all__'
        # depth = 1  # depth = 1的话，如果里面有存在外键或多对多，一对多等关系，则会继续序列化他们的数据，所有数据都会展示
        fields = ('id', 'name', 'price', 'author_list', 'publish', 'publish_name', 'authors')
        extra_kwargs = {
            'publish': {'write_only': True},
            'publish_name': {'read_only': True},
            'authors': {'write_only': True},
            'author_list': {'read_only': True},
        }

# 自定制频率限制